<template>
  <div>
    <h4>我的任务单</h4>
    <p>这里将显示用户的任务列表，包含"进行中"、"已完成"等状态的筛选。</p>
    <el-tabs v-model="activeTab"  @tab-click="handleTabClick">
      <el-tab-pane label="进行中" name="processing">
        <el-table :data="tasks.processing" style="width: 100%">
          <el-table-column prop="orderNo" label="订单号"></el-table-column>
          <el-table-column prop="orderTitle" label="任务标题"></el-table-column>
          <el-table-column prop="rewardAmount" label="订单金额" width="120"></el-table-column>
          <el-table-column prop="estimatedEndTime" label="截止时间" width="180"></el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="mini" @click="viewTask(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="已完成" name="completed">
        <el-table :data="tasks.completed" style="width: 100%">
           <el-table-column prop="orderNo" label="订单号"></el-table-column>
          <el-table-column prop="orderTitle" label="任务标题"></el-table-column>
          <el-table-column prop="rewardAmount" label="订单金额" width="120"></el-table-column>
          <el-table-column prop="estimatedEndTime" label="完成时间" width="180"></el-table-column>
           <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button size="mini" @click="viewTask(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="服务费" name="error">
         <el-table :data="tasks.error" style="width: 100%">
          <el-table-column prop="orderNo" label="订单号"></el-table-column>
          <el-table-column prop="orderTitle" label="任务标题"></el-table-column>
          <el-table-column prop="rewardAmount" label="订单金额" width="120"></el-table-column>
          <el-table-column prop="introduce" label="任务描述"></el-table-column>
        </el-table>
      </el-tab-pane>
       <el-tab-pane label="半成品" name="half">
        <el-table :data="tasks.half" style="width: 100%">
           <el-table-column prop="orderNo" label="订单号"></el-table-column>
          <el-table-column prop="orderTitle" label="任务标题"></el-table-column>
          <el-table-column prop="rewardAmount" label="订单金额" width="120"></el-table-column>
          <el-table-column prop="estimatedEndTime" label="完成时间" width="180"></el-table-column>
           <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button size="mini" @click="viewTask(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="退单" name="chargeback">
        <el-table :data="tasks.chargeback" style="width: 100%">
          <el-table-column prop="orderNo" label="订单号" width="150"></el-table-column>
          <el-table-column prop="orderTitle" label="任务标题" width="200"></el-table-column>
          <el-table-column prop="techType" label="程序类型"></el-table-column>
          <el-table-column prop="rewardAmount" label="订单金额" width="120"></el-table-column>
          <el-table-column prop="introduce" label="任务描述"></el-table-column>
          <el-table-column prop="chargebackReason" label="退单理由" width="180"></el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button size="mini" @click="viewTask(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
       <el-tab-pane label="订单任务" name="orderTask">
        <el-table :data="tasks.orderTask" style="width: 100%">
          <el-table-column prop="gradOrdersNo" label="订单号"></el-table-column>
          <el-table-column prop="gradOrdersTitle" label="任务标题"></el-table-column>
          <el-table-column prop="finalTaskAmount" label="中单价格"></el-table-column>
          <el-table-column prop="taskState" label="任务状态" width="120">
            <template slot-scope="scope">
              {{ getTaskStatusLabel(scope.row.taskState) }}
            </template>
          </el-table-column>
          <el-table-column prop="withdrawalStatus" label="提现状态" width="180">
            <template slot-scope="scope">
              {{ getWithdrawalStatusLabel(scope.row.withdrawalStatus) }}
            </template>
          </el-table-column>
           <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.taskState === '3' && (scope.row.withdrawalStatus === '1' || scope.row.withdrawalStatus === '3')"
                size="mini"
                type="primary"
                @click="handleWithdrawal(scope.row)"
              >提现</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      title="任务详情"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose">
      <div v-if="currentTask">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单号">{{ currentTask.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="任务标题">{{ currentTask.orderTitle }}</el-descriptions-item>
          <el-descriptions-item label="是否加急">{{ getUrgentLabel(currentTask.isUrgent) }}</el-descriptions-item>
          <el-descriptions-item label="程序类型">{{ currentTask.techType }}</el-descriptions-item>
          <el-descriptions-item v-if="activeTab === 'chargeback'" label="退单理由">{{ currentTask.chargebackReason }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">{{ currentTask.rewardAmount }}</el-descriptions-item>
          <el-descriptions-item label="程序开始时间">{{ currentTask.startTime }}</el-descriptions-item>
          <el-descriptions-item v-if="activeTab !== 'error'" label="截止时间">{{ currentTask.estimatedEndTime }}</el-descriptions-item>
          <el-descriptions-item label="接单时间">{{ currentTask.acceptTime }}</el-descriptions-item>
          <el-descriptions-item label="所需最低信用分">{{ currentTask.requiredCreditScore }}</el-descriptions-item>
          <el-descriptions-item v-if="activeTab === 'completed'" label="完成时间">{{ currentTask.estimatedEndTime }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listTasks,listTaskOrder } from "@/api/system/task";
import { addWithdrawalApplication } from "@/api/dashboard/withdrawalApplication";
import{getType} from "@/api/dashboard/type";

export default {
  name: "MyTasks",
  props: {
    userId: {
      type: [String, Number],
    }
  },
  data() {
    return {
      dialogVisible: false,
      activeTab: 'processing',
      tasks: {
        processing: [],
        completed: [],
        error: [],
        half : [],
        chargeback: [],
        orderTask:[]
      },
      currentTask: null,
      isUrgentOptions: [
        { label: '加急', value: '1' },
        { label: '不加急', value: '0' }
      ],
      taskStatusOptions: [
        { label: '未中单', value: '0' },
        { label: '任务进行中', value: '1' },
        { label: '任务已完成', value: '2' },
        { label: '移交客户', value: '3' },
        { label: '任务结束', value: '4' },
        { label: '技术退单(扣除信用分)', value: '5' },
        { label: '客户退单(补偿款)', value: '6' },
        { label: '拒绝提现', value: '7' }
      ],
      withdrawalStatusOptions: [
        { label: '不可提现', value: '0' },
        { label: '提现首款可申请', value: '1' },
        { label: '已提现首款', value: '2' },
        { label: '尾款可申请', value: '3' },
        { label: '已提现尾款', value: '4' },
        { label: '首款提现失败', value: '5' },
        { label: '尾款提现失败', value: '6' }
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        acceptedProgrammerId: null,
        gradOrdersId: null,
        orderNo: null,
        orderTitle: null,
        status: null // Add status to queryParams
      },
      total: 0 // Initialize total for pagination
    };
  },
  created() {
    this.getList(); // Call getList on creation
  },
  methods: {
    getUrgentLabel(value) {
      const option = this.isUrgentOptions.find(opt => opt.value === value);
      return option ? option.label : '未知状态';
    },
    getTaskStatusLabel(value) {
      const option = this.taskStatusOptions.find(opt => opt.value === String(value));
      return option ? option.label : '未知状态';
    },
    getWithdrawalStatusLabel(value) {
      const option = this.withdrawalStatusOptions.find(opt => opt.value === String(value));
      return option ? option.label : '未知状态';
    },
    getList() {
      if(this.activeTab !== 'orderTask'){
        let status = this.queryParams.status;
        switch (this.activeTab) {
          case 'processing':
            status = "2";
            break;
          case 'completed':
            status = "5";
            break;
          case 'error':
            status = "7";
            break;
          case 'half':
            status = "6";
            break;
          case 'chargeback':
            status = "4";
            break;
        }
        this.queryParams.status = status;
        listTasks(this.queryParams).then(response => {
          if (this.activeTab === 'processing') {
            this.tasks.processing = response.rows;
          } else if (this.activeTab === 'completed') {
            this.tasks.completed = response.rows;
          } else if (this.activeTab === 'error') {
            this.tasks.error = response.rows;
          } else if (this.activeTab === 'half') {
            this.tasks.half = response.rows;
          } else if (this.activeTab === 'chargeback') {
            this.tasks.chargeback = response.rows;
          }
          this.total = response.total;
        });
      }else{
        this.queryParams.acceptedProgrammerId=parseInt(this.userId);
        listTaskOrder(this.queryParams).then(response => {
          this.tasks.orderTask = response.rows;
          this.total = response.total;
         
        });
      }
    },
    handleTabClick(tab) {
      this.queryParams.pageNum = 1; // Reset page number when changing tabs
      this.activeTab = tab.name; // Update activeTab
      this.getList();
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams.orderNo = null;
      this.queryParams.orderTitle = null;
      this.handleQuery();
    },
   viewTask(task) {
      this.currentTask = task
      this.dialogVisible = true
    },
    handleClose(done) {
      done()
    },
    handleWithdrawal(task) {
      this.$confirm('确定要申请提现吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const withdrawalType = task.withdrawalStatus === '1' ? '1' :
                      task.withdrawalStatus === '3' ? '2' :
                      '';
        let getTypeName = null;
        getType(task.gradOrdersTaskTypeId).then(resp => {
          console.log(resp.data);
          getTypeName = resp.data.orderTaskName;
          const data = {
            gradOrdersId: task.gradOrdersId,
            gradOrdersTaskId:task.id,
            orderTaskTypeName:getTypeName,
            withdrawalType:withdrawalType,
            applicationAmount: task.finalTaskAmount,
          };
          addWithdrawalApplication(data).then(response => {
            this.$message({
              type: 'success',
              message: '提现申请成功!'
            });
            this.getList(); // Refresh the list after successful withdrawal
          }).catch(error => {
            this.$message({
              type: 'error',
              message: '提现申请失败: ' + (error.msg || error.message)
            });
          });
        }).catch(error => {
          this.$message({
            type: 'error',
            message: '获取任务类型失败: ' + (error.msg || error.message)
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消提现'
        });
      });
    }
  }
};
</script> 